﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;

namespace RCSoft.Core
{
    /// <summary>
    /// 通用帮助类
    /// </summary>
    public partial class CommonHelper
    {
        /// <summary>
        /// 保证用户Mail通过或者抛出异常
        /// </summary>
        /// <param name="email">Email</param>
        /// <returns></returns>
        public static string EnsureSubScriberEmailOrThrow(string email)
        {
            string output = EnsureNotNull(email);
            output = output.Trim();
            output = EnsrueMaximumLength(output, 255);

            if (!IsValidEmail(output))
            {
                throw new RCSoftException("Email is not valid.");
            }
            return output;
        }

        /// <summary>
        /// 验证一个邮箱格式
        /// </summary>
        /// <param name="email">邮箱</param>
        /// <returns></returns>
        private static bool IsValidEmail(string email)
        {
            bool result = false;
            if(String.IsNullOrEmpty(email))
                return result;
            email = email.Trim();
            result = Regex.IsMatch(email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
            return result;
        }

        /// <summary>
        /// 确保字符串不超过规定字符长度
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <param name="maxLength">字符串限制长度</param>
        /// <returns>输入长度不超过限制长度返回原字符串，超出则截取限制的长度</returns>
        private static string EnsrueMaximumLength(string str, int maxLength)
        {
            if (String.IsNullOrEmpty(str))
                return str;
            if (str.Length > maxLength)
                return str.Substring(0, maxLength);
            else
                return str;
        }

        /// <summary>
        /// 确保字符串不为空
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <returns>结果</returns>
        private static string EnsureNotNull(string str)
        {
            if (str == null)
                return string.Empty;
            return str;
        }

        public static bool OneToManyCollectionWrapperEnabled
        {
            get
            {
                bool enabled = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["OneToManyCollectionWrapperEnabled"]) &&
                    Convert.ToBoolean(ConfigurationManager.AppSettings["OneToManyCollectionWrapperEnabled"]);
                return enabled;
            }
        }
    }
}
